const Epub = require("./epub")
const fs = require('fs')
const {baseStaticURL,baseStaticPath} =  require("../config")
const AdmZip = require("adm-zip");
const mkdirp = require('mkdirp')
class Book{
    constructor(file){
        //文件的原始名称
        this.originName = file.name
        //文件线上名
        this.name = file.newFileName
        //文件线上地址
        this.url = file.bookUrl
        //文件物理地址
        this.path = file.path

        //标题
        this.title = ""
        //语言
        this.language = ""
        //作者
        this.creator = ""
        //出版社
        this.publisher = ""
        //目录
        this.flow = ""
        //封面物理路径
        this.coverPath = ""
        //封面线上地址
        this.coverURL = ""
        //根路径
        this.rootUrl = ""

        //解压路径(物理目录)
        let unzipName = file.newFileName.split(".")[0];
        this.unzipPath = `${baseStaticPath}/unzip/${unzipName}`
        //解压路径(线上目录)
        this.unzipURL = `${baseStaticURL}/unzip/${unzipName}`
    }

    parse(){
        return new Promise((resolve,reject)=>{
            const epub = new Epub(this.path);
            epub.on('end', ()=>{
                const {
                    title,
                    language,
                    creator,
                    publisher,
                    cover:coverId
                } = epub.metadata

                this.title = title;
                this.language = language;
                this.creator = creator;
                this.publisher = publisher;
                this.rootUrl = epub.rootFile;
                this.flow  = epub.flow
                epub.getImage(coverId, (error, fileBuffer, mimeType) => {
                    //解压
                    if(!fs.existsSync(this.unzipPath)){
                        //解压目录不存在  我们需要自动创建一个
                        mkdirp.sync(this.unzipPath)
                    }
                    const zip = new AdmZip(this.path);
                    zip.extractAllTo(this.unzipPath, true);

                    if(fileBuffer === undefined) {
                      resolve();
                      return;
                    }
                    //封面操作
                    let suffix = mimeType.split("/").pop();
                    let coverName = this.name.split(".")[0];
                    let coverPath = `${baseStaticPath}//img//${coverName}.${suffix}`;
                    this.coverPath=coverPath;
                    fs.writeFileSync(coverPath,fileBuffer);
                    this.coverURL= `${baseStaticURL}/img/${coverName}.${suffix}`
                    resolve()
                })
            })
            epub.parse()
        })
    }
}

module.exports = Book;